<template>
    <div class="psc-main-page-public">
        <lots-list-layout>
            <template #header-search>
                <md-popover placement="bottom" title="" trigger="click" @after-enter="onGridSelectShow"
                    :width="440"
                >
					<div class="grid-select-wrap">
						<p class="selected-value">{{ selectedValue.x }} x {{ selectedValue.y }}</p>
						<DGridSelect
							v-if="poperMounted"
							ref="gridSelect"
							:change="selectAreaChange"
							:select="selectedGrid"
							:rowNum="18"
							:colNum="18" />
					</div>
                    <template #reference>
                        <md-button slot="reference" type="primary">选择网格</md-button>
                    </template>
					
				</md-popover>
                <md-button type="primary" @click="addLayout">添加布局</md-button>
            </template>
            <template #header-button><md-button type="primary" :loading="saveLoading" @click="save">保存</md-button></template>
            <template #list>
                <DLayer ref="layout" :templateOptions="templateOptions" :onDeleteArea="onDeleteArea" />
            </template>
        </lots-list-layout>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue';
import DGridSelect from '@/components/DGridSelect';
import DLayer from '@/components/DLayer';
import { MdMessageBox, MdMessage } from 'mdesign3';
const selectedValue = reactive({x: 0, y: 0});
const defaultTemplateOptions = {
    rowNum: 8, //	行数
    colNum: 8, //	列数
    //	网格区域
    // {
    // 	coordinate: [1, 1, 3, 4], //	网格区域坐标范围
    // 	bgColor: randomColor(), //	网格颜色
    // },
    areaInfo: [],
};
const layout = ref();

const poperMounted = ref(false);

function onGridSelectShow() {
    //	初始化网格筛选器
    nextTick(() => {
        poperMounted.value = true; // 避免poper展示后实际canvas画布元素未渲染
    });
}
const  templateOptions = ref(JSON.parse(JSON.stringify(defaultTemplateOptions)));

function selectAreaChange(colCount: number, rowCount: number) {
    selectedValue.x = colCount;
    selectedValue.y = rowCount;
}

function selectedGrid(colCount, rowCount) {
  
        MdMessageBox.confirm(
        '确认清空当前布局，重新设计？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        },
    )
        .then(() => {
            templateOptions.value = Object.assign({}, templateOptions.value, {
                rowNum: rowCount,
                colNum: colCount,
                areaInfo: [],
            });
            console.log(templateOptions.value)
        });
}


function onDeleteArea(areaItem) {
    const  opts = JSON.parse(JSON.stringify(templateOptions.value));
    const index = opts.areaInfo.indexOf(areaItem);
    opts.areaInfo.splice(index, 1);
    templateOptions.value = opts
}


function addLayout() {
	//添加模板布局
    console.log(layout.value.layer)
    layout.value.layer.startAreaSelect(
        confrimAddMoudle,
        onAreaDuplicate,
        onAreaOverLap,
    );
}

function confrimAddMoudle(startColIndex, startRowIndex, endColIndex, endRowIndex, bgColor) {
	//	确认添加布局
    const  opts = JSON.parse(JSON.stringify(templateOptions.value));
    opts.areaInfo.push({
        coordinate: [startRowIndex + 1, startColIndex + 1, endRowIndex + 1, endColIndex + 1],
        bgColor: bgColor,
    });
    templateOptions.value = opts
}

function onAreaDuplicate(e, rowIndex, colIndex) {
    //所选区域重复
    MdMessageBox.confirm(
        `当前单元格${rowIndex}-${colIndex}已被使用`,
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
}


function onAreaOverLap(startColIndex, startRowIndex, endColIndex, endRowIndex) {

    MdMessageBox.confirm(
        `所选区域重复`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {})
    .catch(() => {})
    .finally(() => {
        layout.value.layer.render();
    });
			
}


function onSelectAreaChange(colCount, rowCount) {
    selectedValue.x = colCount;
    selectedValue.y = rowCount;
}

function handleSave() {
    this.$MdConfirm(this.t('是否确认提交'), this.t('确认'), {
        confirmButtonText: this.t('确定'),
        cancelButtonText: this.t('取消'),
        type: 'warning',
    })
        .then(async () => {
            this.saveLoading = true;
            const thumbUrl = await uploadDomThumbUrl(this.$refs.DLayer.$el, this.templateOptions.name);
            const res = await frameApi.updateFrameDetail({
                id: this.$route.query.id,
                ...this.templateOptions,
                thumbUrl,
            });
            if (res.code === '0') {
                this.$MdMessage.success(this.t('提交成功') + '，' + this.t('即将返回') + '...');
                setTimeout(() => {
                    this.$store.commit('user/DEL_TAG', this.$route);
                    this.$router.go(-1);
                }, 1000);
            }
        })
        .catch(() => {})
        .finally(() => {
            this.$refs.DLayer.layer.render();
            this.saveLoading = false;
        });
}
</script>
<style lang="scss" scoped>
	.template-generator {
		box-sizing: border-box;
		height: 100%;
		border-top: 1px solid rgba(0, 0, 0, 0);
		box-sizing: border-box;
		background-color: #fff;
	}
	.d-grid-select {
		width: 400px;
		height: 400px;
	}
	
	.grid-select-wrap {
		margin: 0 20px;
		.selected-value {
			font-size: 16px;
			font-weight: 600;
			text-align: center;
			margin: 5px;
		}
	}

	.d-layer {
		width: 100%;
		height: 100%;
	}
	.tool-bar {
		margin: 20px;
	}
	.template-operator {
		> .md-button {
			margin-left: 15px;
		}
	}
</style>